<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
        <Editor style="height: 300px; overflow-y: hidden;" :defaultConfig="editorConfig" v-model="valueHtml"
            @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed"
            @onFocus="handleFocus" @onBlur="handleBlur" />
    </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
// 正确导入 wangEditor 组件 (Vue 3)
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'

// 定义props和emit
const props = defineProps({
    modelValue: {
        type: String,
        default: '<p></p>'
    },
    height: {
        type: String,
        default: '300px'
    },
    placeholder: {
        type: String,
        default: '请输入内容...'
    },
    uploadUrl: {
        type: String,
        default: '/api/upload'
    }
});

const emit = defineEmits(['update:modelValue', 'change']);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref(props.modelValue);

// 监听props的变化，更新编辑器内容
watch(() => props.modelValue, (newVal) => {
    if (newVal !== valueHtml.value) {
        valueHtml.value = newVal;
    }
}, { immediate: true });

// 监听编辑器内容变化，向父组件发送更新
watch(() => valueHtml.value, (newVal) => {
    emit('update:modelValue', newVal);
    emit('change', newVal);
}, { deep: true });

// 工具栏配置
const toolbarConfig = {
    excludeKeys: [] // 可以在这里排除不需要的功能按钮
};

// 编辑器配置
const editorConfig = {
    placeholder: props.placeholder,
    MENU_CONF: {}
};

// 配置图片上传
editorConfig.MENU_CONF['uploadImage'] = {
    server: props.uploadUrl,
    fieldName: 'file',
    maxFileSize: 5 * 1024 * 1024, // 5MB
    maxNumberOfFiles: 10,
    allowedFileTypes: ['image/*'],
    metaWithUrl: true,
    customInsert(res, insertFn) {
        // res 即服务端的返回结果
        if (res.code === 0 && res.data) {
            // 插入图片到编辑器
            insertFn(res.data, '', res.data);
            ElMessage.success('图片上传成功');
        } else {
            ElMessage.error(res.msg || '图片上传失败');
        }
    },
    onError(file, err, res) {
        console.error('图片上传出错', file, err, res);
        ElMessage.error('图片上传失败：' + (err.message || '未知错误'));
    }
};

// 配置视频上传
editorConfig.MENU_CONF['uploadVideo'] = {
    server: props.uploadUrl,
    fieldName: 'file',
    maxFileSize: 50 * 1024 * 1024, // 50MB
    maxNumberOfFiles: 5,
    allowedFileTypes: ['video/*'],
    metaWithUrl: true,
    customInsert(res, insertFn) {
        // res 即服务端的返回结果
        if (res.code === 0 && res.data) {
            // 插入视频到编辑器
            insertFn(res.data);
            ElMessage.success('视频上传成功');
        } else {
            ElMessage.error(res.msg || '视频上传失败');
        }
    },
    onError(file, err, res) {
        console.error('视频上传出错', file, err, res);
        ElMessage.error('视频上传失败：' + (err.message || '未知错误'));
    }
};

// 设置编辑器模式
const mode = 'default'; // 或 'simple'

// 组件挂载时，初始化编辑器
onMounted(() => {
    // 如果有初始内容，设置到编辑器
    if (props.modelValue) {
        valueHtml.value = props.modelValue;
    }
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

// 编辑器创建完成时的回调
const handleCreated = (editor) => {
    editorRef.value = editor;
    console.log('富文本编辑器创建成功');
};

// 编辑器内容变化时的回调
const handleChange = (editor) => {
    valueHtml.value = editor.getHtml();
    emit('update:modelValue', valueHtml.value);
    emit('change', valueHtml.value);
};

const handleDestroyed = (editor) => {
    editorRef.value = null;
};

const handleFocus = (editor) => {
    console.log('编辑器获得焦点');
};

const handleBlur = (editor) => {
    console.log('编辑器失去焦点');
};
</script>

<style scoped>
.w-e-text-container {
    height: v-bind('props.height') !important;
}

:deep(.w-e-text-placeholder) {
    font-style: italic;
    color: #d4d4d4;
}

:deep(.w-e-toolbar) {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
}

:deep(.w-e-text-container) {
    border-bottom-left-radius: 4px; 
    border-bottom-right-radius: 4px;
}
</style>